package com.anyou.common.oss;



import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;

/**
* @Description: 腾讯云上传文件
* @author: ylj
* @date: 2022/4/1 17:19
*/
public class TencentOssUtil {

    public static String upload(MultipartFile file) {
        COSCredentials cred = new BasicCOSCredentials(TencentOssConfig.secretId, TencentOssConfig.secretKey);

        ClientConfig clientConfig = new ClientConfig(new Region(TencentOssConfig.regionName));

        COSClient cosclient = new COSClient(cred, clientConfig);

        String originalFilename = file.getOriginalFilename();
        if(originalFilename.indexOf(".")==-1){
            originalFilename=originalFilename+".jpg";
        }
        String fileSub = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        String name = System.currentTimeMillis()+"";
        String key = System.currentTimeMillis()+ fileSub;
        File localFile = null;
        try {
            localFile = new File(key);
            InputStream inputStream = file.getInputStream();
            FileUtils.copyInputStreamToFile(inputStream, localFile);
            localFile = File.createTempFile(name, fileSub);
            file.transferTo(localFile);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        PutObjectRequest putObjectRequest = new PutObjectRequest(TencentOssConfig.bucketName, TencentOssConfig.fileDir+key, localFile);
        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard);
        String fileName = "";
        try {
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            // putobjectResult会返回文件的etag
            //String etag = putObjectResult.getETag();
            //String crc64 = putObjectResult.getCrc64Ecma();
            fileName = TencentOssConfig.baseUrl + TencentOssConfig.fileDir + name + fileSub;
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        // 关闭客户端
        cosclient.shutdown();
        File f = new File(key);
        if(f.exists()){
            f.delete();
        }
        return fileName;
    }


}
